/*
 * @Author: pardon110
 * @Date: 2024-03-23 15:15:02
 * @LastEditors: pardon110@qq.com
 * @LastEditTime: 2024-03-23 19:26:55
 * @FilePath: \days7\geerpc\day3\main\main.go
 * @Description:
 */
package main

import (
	"log"
	"net"
	"sync"
	"time"

	"days7.test/geerpc/day3"
)

type Foo int

type Args struct{ Num1, Num2 int }

func (f Foo) Sum(args Args, reply *int) error {
	*reply = args.Num1 + args.Num2
	return nil
}

func startServer(addr chan<- string) {
	var foo Foo
	if err := day3.Register(&foo); err != nil {
		log.Fatal("register failed: ", err)
	}

	// pick a free port
	l, err := net.Listen("tcp", ":0")
	if err != nil {
		log.Fatal("network error: ", err)
	}
	log.Println("start rpc server on ", l.Addr())

	addr <- l.Addr().String()
	day3.Accept(l)
}

func main() {
	log.SetFlags(0)
	addr := make(chan string)
	go startServer(addr)
	client, _ := day3.Dial("tcp", <-addr)
	defer func() {
		_ = client.Close()
	}()

	time.Sleep(time.Second)
	var wg sync.WaitGroup
	for i := 0; i < 10; i++ {
		wg.Add(1)
		go func(i int) {
			defer wg.Done()
			args := &Args{Num1: i, Num2: i * i}
			var reply int
			if err := client.Call("Foo.Sum", args, &reply); err != nil {
				log.Fatal("day3 call Foo.Sum error:", err)
			}
			log.Printf("%d + %d = %d", args.Num1, args.Num2, reply)
		}(i)
	}
	wg.Wait()
}
